package net.zxteam.solutions.java.rs_sync;

import java.io.File;
import java.io.IOException;

import net.zxteam.reusable.java.IllegalArgumentNullException;
import net.zxteam.reusable.java.io.Directory;

import org.tigris.subversion.javahl.Revision;
import org.tigris.subversion.javahl.SVNClient;

abstract class SVNRSSyncBase extends RSSync {

	protected final SVNClient svnSource = new SVNClient();
	protected final SVNClient svnDestination = new SVNClient();
	private File tmpWorkFolder;
	protected File sourceLocalCopyPath;
	protected File destinationLocalCopyPath;

	protected SVNRSSyncBase() throws IOException {

		tmpWorkFolder = generateTempWorkFolder();
		sourceLocalCopyPath = new File(tmpWorkFolder, "source");
		destinationLocalCopyPath = new File(tmpWorkFolder, "destination");
	}

	public void setTempDirectory(File directory) {

		if(directory == null)
			throw new IllegalArgumentNullException("directory");
		
		tmpWorkFolder = directory;
		sourceLocalCopyPath = new File(tmpWorkFolder, "source");
		destinationLocalCopyPath = new File(tmpWorkFolder, "destination");
	}
	
	@Override
	public void setSourceAuthentication(String username, String password) {

		if(username != null) System.out.println("Source user name: " + username);
		if(password != null) System.out.println("Source user password: " + password);

		this.svnSource.username(username);
		this.svnSource.password(password);
	}

	@Override
	public void setDestinationAuthentication(String username, String password) {

		if(username != null) System.out.println("Destination user name: " + username);
		if(password != null) System.out.println("Destination user password: " + password);

		this.svnDestination.username(username);
		this.svnDestination.password(password);
	}

	protected final void prepareLocalWorkCopy(SVNClient svn, String repUrl, Revision rev, File localPath) throws Exception {

		String localPathStr = localPath.getPath();

		if(Directory.exists(localPath)) {

			boolean isLocalPathDirty = false;

			if(isLocalPathDirty) {	// If localWorkCopy is broken

				Directory.remove(localPath);	// remove directory completely
				svn.checkout(repUrl, localPathStr, rev, true);	// checkout again
			}
			else {
				svn.update(localPathStr, rev, true);
			}
		}
		else {
			svn.checkout(repUrl, localPathStr, rev, true);
		}
	}

	private File generateTempWorkFolder() throws IOException {

		File file = Directory.newTempDirectory();
		
		//return new File("C:\\t");
		//return new File("/Users/maxim.anurin/tmp/rs-sync");
		//return new File("/tmp/rs-sync");
		return file;
	}
}
